from flask import Response
import json
from typing import Any, Dict, Optional, Union
from dataclasses import asdict

class JsonResponse(Response):
    def __init__(
        self,
        data: Any = None,
        message: str = "success",
        status: int = 200,
        headers: Optional[Dict] = None,
        **kwargs
    ):
        # Handle data conversion
        processed_data = {}
        if data is not None:
            if hasattr(data, '__dataclass_fields__'):
                processed_data = asdict(data)
            elif hasattr(data, 'to_dict'):
                processed_data = data.to_dict()
            elif isinstance(data, (dict, list, str, int, float, bool)):
                processed_data = data
            else:
                try:
                    processed_data = dict(data)
                except (TypeError, ValueError):
                    processed_data = str(data)

        self.response_data = {
            "code": status,
            "message": message,
            "data": processed_data
        }
        
        # 添加额外的字段
        self.response_data.update(kwargs)

        # 确保响应数据可以被序列化
        response_json = self.serialize_response(self.response_data)
        
        # 存储原始响应数据，用于日志记录
        self._raw_response = self.response_data

        super().__init__(
            response=response_json,
            status=200,
            headers=headers,
            mimetype='application/json'
        )
    def __str__(self):
        """用于日志记录的字符串表示"""
        try:
            return json.dumps(self._raw_response, ensure_ascii=False)
        except:
            return f"Response(status={self._raw_response.get('code', 'unknown')})"

    def __repr__(self):
        """用于调试的字符串表示"""
        return self.__str__()

    def serialize_response(self, data: Any) -> str:
        """安全序列化响应数据"""
        try:
            return json.dumps(data, ensure_ascii=False)
        except (TypeError, ValueError):
            # 如果序列化失败，返回基本错误信息
            return json.dumps({
                "code": 500,
                "message": "Response serialization failed",
                "data": str(data)
            }, ensure_ascii=False)

    @classmethod
    def error(
        cls,
        message: str = "error",
        status: int = 400,
        data: Any = None,
        **kwargs
    ) -> 'JsonResponse':
        """
        快速创建错误响应
        """
        return cls(
            message=message,
            status=status,
            data=data,
            **kwargs
        )

    @classmethod
    def success(
        cls,
        data: Any = None,
        message: str = "success",
        **kwargs
    ) -> 'JsonResponse':
        """
        快速创建成功响应
        """
        return cls(
            data=data,
            message=message,
            status=200,
            **kwargs
        )